package com.tencent.qcloud.qiaoqiao.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.Toast;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.tencent.qcloud.qiaoqiao.R;
import com.tencent.qcloud.qiaoqiao.common.utils.FileUtils;
import com.tencent.qcloud.qiaoqiao.common.utils.TCConstants;
import com.tencent.qcloud.qiaoqiao.common.utils.TCUtils;
import com.tencent.qcloud.qiaoqiao.common.widget.ShortVideoDialog;
import com.tencent.qcloud.qiaoqiao.login.TCUserMgr;
import com.tencent.qcloud.qiaoqiao.ui.BaseActivity;
import com.tencent.qcloud.qiaoqiao.ui.fragment.ChartFragment;
import com.tencent.qcloud.qiaoqiao.ui.fragment.HomeFragment;
import com.tencent.qcloud.qiaoqiao.ui.fragment.LikeUserVideoFragment;
import com.tencent.qcloud.qiaoqiao.ui.fragment.MineFragment;
import com.tencent.qcloud.qiaoqiao.ui.tools.TabEntity;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ActivityUtils;
import com.tencent.qcloud.qiaoqiao.ui.view.MyViewPager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainUIActivity extends BaseActivity {

    private CommonTabLayout mTabLayout_2;
    //    private String[] mTitles = {"首页", "收藏", "","发现", "我"};
//    private int[] mIconSelectIds = {
//            0, 0,
//            R.mipmap.home_photo,0, 0};
//    private int[] mIconUnselectIds = {
//            0,  0,
//            R.mipmap.home_photo, 0, 0};
    private String[] mTitles = {"", "", "", "", ""};
    private int[] mIconSelectIds = {R.mipmap.home_tab1, R.mipmap.home_tab2, R.mipmap.home_tab5, R.mipmap.home_tab3, R.mipmap.home_tab4};
    private int[] mIconUnselectIds = {R.mipmap.home_tab1, R.mipmap.home_tab2, R.mipmap.home_tab5, R.mipmap.home_tab3, R.mipmap.home_tab4};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private MyViewPager vp;
    private ShortVideoDialog mShortVideoDialog;
    private long mLastClickPubTS = 0;

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int type = intent.getIntExtra("type",0);
        if (type==1){
            vp.setCurrentItem(0);
        } else if (type==2){
            vp.setCurrentItem(4);
        }else if (type==3){
           VideoLoginActivity.StartActivity();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ArrayList<Fragment> fragments = new ArrayList<>();
//        fragments.add(TradeUserInfoFragment.newInstance());
//        fragments.add(HomeFragment2.newInstance("首页"));
        fragments.add(HomeFragment.newInstance());
        fragments.add(LikeUserVideoFragment.newInstance());
        fragments.add(LikeUserVideoFragment.newInstance());
        fragments.add(ChartFragment.newInstance());
        fragments.add(MineFragment.newInstance(null));
//        TradeUserInfoActivity.startMyActivity(this);
        vp = (MyViewPager) findViewById(R.id.vp);
        vp.setOffscreenPageLimit(5);
        VpAdapter adapter = new VpAdapter(getSupportFragmentManager(), fragments);
        vp.setAdapter(adapter);

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        mTabLayout_2 = (CommonTabLayout) findViewById(R.id.homeTbaLayout);
        mTabLayout_2.setTabData(mTabEntities);
        mTabLayout_2.setOnTabSelectListener(new OnTabSelectListener() {
            int topIndex;

            @Override
            public void onTabSelect(int position) {
                if (position == 2) {
                    showSelect();
                    mTabLayout_2.setCurrentTab(topIndex);
                    return;
                }
                if (position == 3||position == 4) {
                    if (TCUserMgr.getInstance().hasUser()) {
                        mTabLayout_2.setCurrentTab(topIndex);
                        ActivityUtils.startActivity(VideoLoginActivity.class);
                    } else {
                        vp.setCurrentItem(position);
                    }
                    return;
                }
                topIndex = position;
                vp.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        vp.setCurrentItem(0);
//        mTabLayout_2.setTextSelectColor(ContextCompat.getColor(this, R.color.mind));
//        mTabLayout_2.setTextUnselectColor(ContextCompat.getColor(this, R.color.whiteColor));
//        mTabLayout_2.setTextsize(16);
//        mTabLayout_2.setUnderlineHeight(0);

        if (checkPermission()) {
            return;
        }
        copyLicenceToSdcard();
        mShortVideoDialog = new ShortVideoDialog();
    }

    private void showSelect() {
        if (TCUserMgr.getInstance().hasUser()) {
            Intent intent = new Intent(MainUIActivity.this, VideoLoginActivity.class);
            startActivity(intent);
        } else {
            // 防止多次点击
            if (System.currentTimeMillis() - mLastClickPubTS > 1000) {
                mLastClickPubTS = System.currentTimeMillis();
                if (mShortVideoDialog.isAdded())
                    mShortVideoDialog.dismiss();
                else
                    mShortVideoDialog.show(getFragmentManager(), "");
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (TextUtils.isEmpty(TCUserMgr.getInstance().getUserToken())) {
            if (TCUtils.isNetworkAvailable(this) && !TCUserMgr.getInstance().hasUser()) {
                TCUserMgr.getInstance().autoLogin(null);
            }
        }
    }

    private void copyLicenceToSdcard() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String sdcardFolder = getExternalFilesDir(null).getAbsolutePath();
                File sdcardLicenceFile = new File(sdcardFolder + File.separator + TCConstants.UGC_LICENCE_NAME);
                if (sdcardLicenceFile.exists()) {
                    return;
                }
                try {
                    FileUtils.copyFromAssetToSdcard(MainUIActivity.this, TCConstants.UGC_LICENCE_NAME, sdcardFolder);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return true;
                }
            }
        }
        return false;
    }

    private class VpAdapter extends FragmentPagerAdapter {
        private List<Fragment> data;

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
        }

        public VpAdapter(FragmentManager fm, List<Fragment> data) {
            super(fm);
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Fragment getItem(int position) {
            return data.get(position);
        }
    }

    long firstTime;
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();

            if (secondTime - firstTime > 800) {//如果两次按键时间间隔大于800毫秒，则不退出 
                Toast.makeText(MainUIActivity.this, "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                firstTime = secondTime;//更新firstTime 
                return true;
            } else {
                System.exit(0);//否则退出程序 
            }
        }
        return super.onKeyUp(keyCode, event);
    }

}
